#include <string.h>
#include <cstdint.h>

size_t strlen ( const char* str )
{
		size_t	len=0;
		while (str[len++] != 0); /* careful! MSVC++ optomization might embed call to strlen()*/
		return len;
}

void * memset ( void * ptr, int value, size_t num )
{
	char *p = (char *) ptr;
	unsigned char val = (unsigned char) value;
	size_t i;
	for (i = 0;i < num;i++)
		*p++ = val;
	return ptr;
}

void * memsetw ( void * ptr, int value, size_t num )
{
	short *p = (short *) ptr;
	unsigned short val = (unsigned short) value;
	size_t i;
	for (i = 0;i < num;i++)
		*p++ = val;
	return ptr;
}

void * memcpy ( void * destination, const void * source, size_t num )
{
	char *p = (char *) destination;
	char *s = (char *) source;
	size_t i;
	for (i = 0;i < num;i++)
		*p++ = *s++;
	return destination;
}

char * strcpy ( char * destination, const char * source )
{
	return (char *) memcpy(destination,source,strlen(source));
}

void *memcpy_o(void *dst_ptr, const void *src_ptr, size_t count,void * buf)
{
	memcpy(buf,src_ptr,count);
	return memcpy(dst_ptr,buf,count);
}

int strcmp ( const char * str1, const char * str2 )
{
	int pos = 0;
	int len = strlen(str1) - 1;
	if (len != (strlen(str2) - 1))
		return 1;
	for (pos = 0;pos < len;pos++)
		if (str1[pos] != str2[pos]){
			return 1;
		}
	return 0;
}

int strcmpn ( const char * str1, const char * str2, size_t num)
{
	uint32_t pos = 0;
	if (strlen(str1) < num)
		return 1;
	if (strlen(str2) < num)
		return 1;
	for (pos = 0;pos < num;pos++)
		if (str1[pos] != str2[pos])
			return 1;
	return 0;
}

int startswith ( const char * str1, const char * str2){
	return strcmpn(str1,str2,strlen(str2)-1);
}

char *strcat(char *s, const char *append)
{
	char *save = s;

	for (; *s; ++s);
	while ((*s++ = *append++) != 0);
	return(save);
}


char * strtok(char *s, const char *delim)
{
	char *spanp;
	int c, sc;
	char *tok;
	static char *last;


	if (s == 0 && (s = last) == 0)
		return (0);

	/*
	 * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
	 */
cont:
	c = *s++;
	for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
		if (c == sc)
			goto cont;
	}

	if (c == 0) {		/* no non-delimiter characters */
		last = 0;
		return (0);
	}
	tok = s - 1;

	/*
	 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
	 * Note that delim must have one NUL; we stop if we see that, too.
	 */
	for (;;) {
		c = *s++;
		spanp = (char *)delim;
		do {
			if ((sc = *spanp++) == c) {
				if (c == 0)
					s = 0;
				else
					s[-1] = 0;
				last = s;
				return (tok);
			}
		} while (sc != 0);
	}
	/* NOTREACHED */
}